﻿using AF_Application.Interface.Cache;
using AF_Cache.Session;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;

namespace AF_Auth
{
    public class WeiXinAuthHelper
    {
        public static string AuthKey = "AuthCache";
        public string AuthReturnUrl = "";
        string CampaignId = "";
        string Debug = "";
        ISessionCacheProvider SessionCacheProvider = null;

        public WeiXinAuthHelper()
        {
            SessionCacheProvider = AF_IOC.IOC.Instance.Get<ISessionCacheProvider>();
            Debug = ConfigurationManager.AppSettings["AuthDebug"].ToString();
            CampaignId = ConfigurationManager.AppSettings["CampaignId"].ToString();
            System.Collections.Specialized.NameValueCollection QueryStrings = System.Web.HttpContext.Current.Request.QueryString;
            if (QueryStrings != null)
            {
                foreach (string key in QueryStrings.AllKeys)
                {
                    SessionCacheProvider.Set<string>("UrlParam_" + key, QueryStrings[key], 300);
                }
            }
        }

        string AuthUrl
        {
            get { return "http://auth.afocus.com.cn/DoAuth.ashx?campaignid=" + CampaignId + "&trycount=0&t=" + DateTime.Now.Ticks; }
        }
        string DebugAuthUrl
        {
            get { return "http://auth.afocus.com.cn/DebugAuth.ashx?campaignid=" + CampaignId + "&trycount=0&t=" + DateTime.Now.Ticks; }
        }
        public bool CurrentUserAuthed
        {
            get
            {
                return CurrentUser != null;
            }
        }

        private WeixinAuthInfo _CurrentUser = null;
        public WeixinAuthInfo CurrentUser
        {
            get
            {
                if (_CurrentUser == null)
                {
                    _CurrentUser = SessionCacheProvider.Get<WeixinAuthInfo>(AuthKey);
                }
                return _CurrentUser;
            }
        }

        public bool CheckAuth()
        {
            bool result = CurrentUserAuthed;
            if (!result)
            {
                if (Debug == "true")
                {
                    System.Web.HttpContext.Current.Response.Redirect(DebugAuthUrl, true);
                }
                else
                {
                    System.Web.HttpContext.Current.Response.Redirect(AuthUrl, true);
                }
            }
            return result;
        }

        public string GetUrlParam(string key)
        {
            return SessionCacheProvider.Get<string>("UrlParam_" + key);
        }

        public bool RemoveUrlParam(string key)
        {
            return SessionCacheProvider.Remove("UrlParam_" + key);
        }
    }
}
